﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using FFIV.Lib.IView.Categories;
using FFIV.Lib.Model;

public partial class Views_Categories_List : System.Web.UI.UserControl, IListCategory
{
	protected void Page_Load(object sender, EventArgs e)
	{

	}

	public CategoryNode Categories
	{
		set
		{
			BuildCategoriesList(value.Children);
			if (value.Children.Count > 0)
			{
				lb_Categories.SelectedIndex = 0;
			}
		}
	}

	public int SelectedCategoryId
	{
		get
		{
			if (lb_Categories.SelectedIndex >= 0)
			{
				return Convert.ToInt32(lb_Categories.SelectedValue);
			}
			else
			{
				return 0;
			}
		}
		set
		{
			foreach (ListItem item in lb_Categories.Items)
			{
				int id = Convert.ToInt32(item.Value);
				if (id == value)
				{
					lb_Categories.SelectedIndex = lb_Categories.Items.IndexOf(item);
				}
			}
		}
	}

	private void BuildCategoriesList(IEnumerable<CategoryNode> datas)
	{
		foreach (CategoryNode data in datas)
		{
			ListItem item = new ListItem();
			item.Text = GetFormattedName(data);
			item.Value = data.Id.ToString();


			lb_Categories.Items.Add(item);

			BuildCategoriesList(data.Children);
		}
	}

	private string GetFormattedName(CategoryNode data)
	{
		const char nbsp = (char)0xA0;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < data.Depth - 1; i++)
		{
			sb.Append(nbsp);
			sb.Append(nbsp);
			sb.Append(nbsp);
		}
		sb.Append(data.Name);
		return sb.ToString();
	}
}
